import fs from 'fs';
import { fromMarkdown } from 'mdast-util-from-markdown';

const markdown = fs.readFileSync('./CHANGELOG.md', 'utf-8');

const ast = fromMarkdown(markdown);
let str = ast.children[0].children[0].value.trim();
const regex = /([^\s]+) \(([^)]+)\)/;
const match = str.match(regex);

const result = {
  version: match[1] || '',
  time: match[2] || '',
  fns: [],
};

let currentSection = null;

ast.children.forEach((node, index) => {
  if (node.type === 'heading' && node.depth === 3) {
    currentSection = {
      title: node.children[0].value.trim(),
      lists: ast.children[index + 1].children.map(listNode => {
        if (listNode.type === 'listItem') {
          const titleNode = listNode.children.find(child => child.type === 'paragraph');
          const linkNode = titleNode.children.find(child => child.type === 'link');
          const imageNode = titleNode.children.find(child => child.type === 'image');
          const listNodes = listNode.children.find(child => child.type === 'list');
          return {
            title: titleNode ? titleNode.children[0].value.trim() : '',
            desc: listNodes
              ? listNodes.children.map(item => {
                  const descNode = listNode.children.find(child => child.type === 'paragraph');
                  const desc = descNode ? descNode.children[0].value.trim() : '';
                  return desc;
                })
              : [],
            url: imageNode ? imageNode.url : '',
            link: linkNode ? linkNode.url : '',
            author: linkNode ? linkNode.children[0].value.trim() : '',
          };
        }
      }),
    };
    result.fns.push(currentSection);
  }
});

// console.log(result.fns[0].lists);
console.log(result);

fs.writeFileSync('./result777.json', JSON.stringify(result, null, 2));
